﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inspired.Euler
{
    public static class Problem021
    {
        /// <summary>
        ///  Evaluate the sum of all amicable pairs under 10000.
        /// </summary>
        static void Main()
        {
            Func<long, long> d = n => n.Divisors2().Sum() - n;

            (   from a in Enumerable.Range(1, 10000)
                let  b = d(a)
                where a != b && d(b) == a
                select a)
                //.Aggregate(-1L, (seed, number) => seed += number)
                .Sum()
                .DisplayAndPause();
        }

        //static long d(long n)
        //{
        //    return n.Divisors().Where(d => d < n).Sum();
        //}

        public static bool IsDivisibleBy(this long number, long factor)
        {
            return number % factor == 0;
        }

        public static IEnumerable<T> Concat<T>(this IEnumerable<IEnumerable<T>> sequences)
        {
            return sequences.SelectMany(sequence => sequence);
        }

        public static IEnumerable<T> Concat<T>(this IEnumerable<T[]> sequences)
        {
            return Concat(sequences.Cast<IEnumerable<T>>());
        }

        public static IEnumerable<long> Divisors2(this long number)
        {
            return (from factor in Enumerable.Range(1, (int)Math.Sqrt(number))
                    where number.IsDivisibleBy((long)factor)
                    select new[] { factor, number / factor }).Concat();
        }  
    }
}
